import React, { useMemo, useState } from 'react';
import { Button, Modal } from 'antd';
import { GModalButtonProps } from './ModalButtonProps';

export const GModalButton = (props: GModalButtonProps) => {
  const [open, setOpen] = useState<boolean>();
  const [loading, setLoading] = useState(false);

  const onButtonClick = (event: any) => {
    props.button?.onClick?.(event);
    setOpen(true);
    props.onOpen?.();
  };

  const handleButton = (
    handler: (() => Promise<any> | void) | undefined,
  ): void => {
    if (handler) {
      setLoading(true);
      try {
        const okReturn = handler();
        if (okReturn) {
          okReturn.then(() => {
            setOpen(false);
          });
        } else {
          setOpen(false);
        }
      } finally {
        setLoading(false);
      }
    } else {
      setOpen(false);
    }
  };

  const onCancel = () => {
    handleButton(props.onCancel);
  };

  const onOk = () => {
    handleButton(props.onOk);
  };

  const button = useMemo(() => {
    return (
      <Button {...props.button} onClick={onButtonClick}>
        {props.text}
      </Button>
    );
  }, [props.button, props.text]);

  const modal = useMemo(() => {
    return (
      <Modal
        maskClosable={false}
        destroyOnClose={true}
        title={props.text}
        {...props.modal}
        open={open}
        onOk={onOk}
        onCancel={onCancel}
        confirmLoading={loading}
      >
        {props.children}
      </Modal>
    );
  }, [props.modal, props.text, open]);

  return (
    <>
      {button}
      {modal}
    </>
  );
};
